import axios from 'axios'
import { Toast } from 'antd-mobile'
import { store } from '@/store'
import history from './history'
import { setToken } from '@/store/actions/login'
import { logout } from '@/store/actions/profile'

export const base = 'http://toutiao.itheima.net'
// 1. 创建新的 axios 实例
const instance = axios.create({
  baseURL: `${base}/v1_0`
})

// 2. 设置请求拦截器和响应拦截器
instance.interceptors.request.use((config) => {
  console.log(history)
  const token = store.getState().login.token
  if (token) {
    config.headers['Authorization'] = `Bearer ${token}`
  }
  return config
})

instance.interceptors.response.use(
  (response) => {
    return response.data?.data
  },
  async (error) => {
    console.log(history)
    // 处理token过期
    if (error.response.status === 401) {
      const config = error.config
      const tokenObj = store.getState().login
      if (!tokenObj.token || !tokenObj.refresh_token) {
        console.log(123)
        // 当token不存在的情况
        history.replace({
          pathname: '/login',
          state: {
            pathname: history.location.pathname
          }
        })
        return Promise.reject(error)
      }
      try {
        // 尝试刷新token
        const res = await axios.put(
          `${config.baseURL}/authorizations`,
          {},
          {
            headers: {
              Authorization: `Bearer ${tokenObj.refresh_token}`
            }
          }
        )
        const newToken = res.data.data.token
        // 同步给本地和reduxToken
        store.dispatch(
          setToken({ token: newToken, refresh_token: tokenObj.refresh_token })
        )
        // 发起原来的请求并返回给页面
        return await instance(config)
      } catch (e) {
        // refresh_token刷新失败
        store.dispatch(logout())
        history.replace({
          pathname: '/login',
          state: {
            pathname: history.location.pathname
          }
        })
        return Promise.reject(error)
      }
    }

    // 通用处理
    if (error?.response?.data?.message) {
      Toast.fail(error?.response?.data?.message, 3, null, false)
    } else {
      Toast.fail('服务器繁忙', 3, null, false)
    }
    return Promise.reject(error)
  }
)

// 3. 导出该 axios 实例
export default instance
